<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input size="mini" v-model="listQuery.schoolName" placeholder="请输入关键字" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter"/>
      <el-button v-waves class="filter-item" size="mini" style="margin-left: 10px;" round @click="handleFilter">
       搜索
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px; float:right" round size="mini" @click.prevent="delData()">
        批量删除
      </el-button>
      <el-upload
        ref="upload"
        class="upload-demo"
        action="doUpload"
        :limit="1"
        :file-list="fileList"
        style="margin-left: 5px; float:right"
        :before-upload="beforeUpload">
        <el-button size="mini" round style="margin-left: 5px; float:right">导入</el-button>
      </el-upload> 
      <el-button v-waves :loading="downloadLoading" class="filter-item" style="margin-left: 10px; float:right" round size="mini" @click="handleDownload">
        模块下载
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px; float:right" round size="mini" @click="handleCreate()">
        新增
      </el-button>
    </div>

    <el-table
      ref="table"
      :key="tableKey"
      v-loading="listLoading"
      :header-cell-style="{background:'#eef1f6',color:'#606266'}"
      stripe
      :data="list"
      highlight-current-row
      style="width: 100%;"
      @selection-change="selectRow"
    >
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column label="序号" align="center" width="80">
        <template slot-scope="{$index}">
          <span>{{ $index+1 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="学校名称" width="250px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.schoolName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="学校地址" width="250px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.address }}</span>
        </template>
      </el-table-column>
      <el-table-column label="法人代表" min-width="100px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.legalRepresentative }}</span>
        </template>
      </el-table-column>
      <el-table-column label="联系人" min-width="100px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.contactPerson }}</span>
        </template>
      </el-table-column>
      <el-table-column label="联系电话" min-width="200px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.phoneNumber }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-button type="text" size="medium" title="编辑" @click="handleUpdate(row)"><i class="el-icon-edit" />
          </el-button>
          <el-button size="medium" type="text" title="删除" @click="handleDelete(row)"><i class="el-icon-delete" />
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" width="25%">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="80px" style="width:300px;" size="mini">
        <el-form-item label="学校名称" prop="schoolName">
          <el-input v-model="temp.schoolName" placeholder="请输入学校名称" />
        </el-form-item>
        <el-form-item label="学校地址" prop="address">
          <el-input v-model="temp.address" placeholder="请输入学校地址" />
        </el-form-item>
        <el-form-item label="法人代表" prop="legalRepresentative">
          <el-input v-model="temp.legalRepresentative" placeholder="请输入法人代表" />
        </el-form-item>
        <el-form-item label="联系人" prop="contactPerson">
          <el-input v-model="temp.contactPerson" placeholder="请输入联系人" />
        </el-form-item>
        <el-form-item label="联系电话" prop="phoneNumber">
          <el-input v-model="temp.phoneNumber" placeholder="请输入联系电话" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" size="mini" @click="dialogStatus==='create'?createData():updateData()">
          保存
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getPage, addSchool, deleteSchool, deleteSchools, updateSchool, addSchoolByTemplate } from '@/api/School'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import XLSX from 'xlsx'
import { valid } from 'mockjs'

export default {
  name: 'ComplexTable',
  components: { Pagination },
  directives: { waves },
  data() {
    return {
      tableKey: 0,
      list: [],
      sels: [],
      item: [],
      total: 0,
      fileList: [], // excel文件列表
      listLoading: true,
      excelData: {
        header: null,
        results: null
      },
      listQuery: {
        schoolName: '',
        page: 1,
        limit: 20
      },
      temp: {
        schoolName: '',
        address: '',
        legalRepresentative: '',
        contactPerson: '',
        phoneNumber: ''
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑学校',
        create: '新增学校'
      },
      dialogPvVisible: false,
      rules: {
        schoolName: [{ required: true, message: '请输入学校名称', trigger: 'blur' }],
        address: [{ required: true, message: '请输入学校地址', trigger: 'blur' }],
        legalRepresentative: [{ required: true, message: '请输入法人代表', trigger: 'blur' }],
        contactPerson: [{ required: true, message: '请输入联系人', trigger: 'blur' }],
        phoneNumber: [{ required: true, message: '请输入联系电话', trigger: 'blur' }]
      },
      downloadLoading: false
    }
  },
  created() {
    this.getList() // 刷新界面
  },
  methods: {
    // 分页显示、模糊查询
    getList() {
      this.listLoading = true
      getPage(this.listQuery).then(res => {
        console.log(res)
        this.list = res.data.records
        this.total = res.data.total
        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 10)
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    resetTemp() {
      this.temp = {
        schoolName: '',
        address: '',
        legalRepresentative: '',
        contactPerson: '',
        phoneNumber: '',
        schoolId: 1
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          addSchool(this.temp).then(() => {
            this.list.unshift(this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: '添加成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.temp.timestamp = new Date(this.temp.timestamp)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          tempData.timestamp = +new Date(tempData.timestamp)
          updateSchool(tempData).then(() => {
            const index = this.list.findIndex(v => v.id === this.temp.id)
            this.list.splice(index, 1, this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: '修改成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        }
      })
    },
    handleDelete(row) {
      this.$confirm(
        '确定要删除吗?删除后不能恢复',
        '系统提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(() => {
          this.$notify({
            title: 'Success',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
          deleteSchool(row)
          for (let i = 0; i < 3; i++) {
            this.getList()
          }
        })
    },
    // 获取表格选中时的数据
    selectRow(sels) {
      this.sels = sels
    },
    // 批量删除
    delData() {
      this.$confirm(
        '确定要删除吗?删除后不能恢复',
        '系统提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(() => {
          for (let i = 0; i < this.sels.length; i++) {
            this.item[i] = this.sels[i].schoolId
          }
          deleteSchools(this)
          this.$notify({
            title: 'Success',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
          for (let i = 0; i < 3; i++) {
            this.getList()
          }
        })
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['序号', '学校名称', '学校地址', '法人代表', '联系人', '联系电话']
        const filterVal = []
        const data = this.formatJson(filterVal)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'table-list'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        return v[j]
      }))
    },
    beforeUpload(file) {
      // console.log(file,'文件');
      this.files = file
      const extension = file.name.split('.')[1] === 'xls'
      const extension2 = file.name.split('.')[1] === 'xlsx'
      const isLt5M = file.size / 1024 / 1024 < 5
      if (!extension && !extension2) {
        this.$message.warning('上传模板只能是 xls、xlsx格式!')
        return
      }
      if (!isLt5M) {
        this.$message.warning('上传模板大小不能超过 5MB!')
        return
      }
      this.fileName = file.name
      setTimeout(() => {
        this.submitUpload()
      }, 500)
      return false // 返回false不会自动上传
    },

    // 上传excel
    submitUpload(e) {
      console.log('上传' + this.files.name)
      if (this.fileName == '') {
        this.$message.warning('请选择要上传的文件！')
        return false
      }
      const fileFormData = new FormData()
      fileFormData.append('file', this.files, this.fileName)
      // 调用后台接口函数
      addSchoolByTemplate(fileFormData).then(() => {
        this.$notify({
          title: 'Success',
          message: '添加成功',
          type: 'success',
          duration: 2000
        })
        this.getList()
      })
    }
  }
}
</script>

<style>
.el-dialog__header {
  background: #e4eaf3;
}

</style>
